const Admin = require('../dbs/models/admin')

const apiAuthentication = [
  '/api/article/add',
  '/api/article/del',
  '/api/article/update',
  '/api/article/admin/query',
  '/api/article/admin/detail',
  '/api/tag/get',
  '/api/tag/add',
  '/api/article/del'
]

const checkToken = (url) => {
  // 是否鉴权
  let authentication = false
  apiAuthentication.map(item => {
    url.includes(item) && (authentication = true)
  })
  return authentication
}

function getTimeStamp () {
  return Math.round(new Date())
}
module.exports = () => {
  return async (ctx, next) => {

    // 校验接口是否鉴权
    if (checkToken(ctx.request.url)) {
      let token = ctx.request.header.authorization
      if (!token) {
        ctx.body = {
          code: -1,
          msg: '缺少token'
        }
      } else {
        // 校验token是否 存在
        const user = await Admin.findOne({token: token})
        if (!user) {
          ctx.body = {
            code: -1,
            msg: '无效token'
          }
        } else {
          if (getTimeStamp() > user.expireTime) {
            ctx.body = {
              code: -1,
              msg: 'token失效，请重新获取'
            }
          } else {
            await next()
          }
        }
      }
    } else {
      await next()
    }
  }
}